package com.my.assembly;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.laojiang.imagepickers.ImagePicker;
import com.laojiang.imagepickers.data.MediaDataBean;
import com.my.assembly.bridge.BridgeWebView;
import com.my.assembly.bridge.CallBackFunction;
import com.my.assembly.event.WeChatCodeEvent;
import com.my.assembly.event.WeChatPayEvent;
import com.my.assembly.handler.ClosePageHandler;
import com.my.assembly.handler.OpenAlbumHandler;
import com.my.assembly.handler.OpenVideoHandler;
import com.my.assembly.handler.PayHandler;
import com.my.assembly.handler.RecordHandler;
import com.my.assembly.handler.WeChatLoginHandler;
import com.my.assembly.handler.XfunVoiceHandler;
import com.my.assembly.utils.HandlerUtils;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.WebChromeClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

import static com.my.assembly.handler.OpenAlbumHandler.REQUEST_CODE;
import static com.my.assembly.handler.OpenAlbumHandler.RESULT_CODE;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    public static final String WX_APPID = "wx725aa31f5a2da818";
    private IWXAPI api;

    private BridgeWebView mWebView;

    private OpenAlbumHandler mOpenAlbumHandler;
    private OpenVideoHandler mOpenVideoHandler;
    private PayHandler mPayHandler;
    private WeChatLoginHandler mWeChatLoginHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        mWebView = findViewById(R.id.webview);
        initWebView();
        initWeChat();
        mWebView.setWebChromeClient(new WebChromeClient());
        mOpenAlbumHandler = new OpenAlbumHandler(this, mWebView);
        mOpenVideoHandler = new OpenVideoHandler(this, mWebView);
        mPayHandler = new PayHandler(this, api);
        mWeChatLoginHandler = new WeChatLoginHandler(this, api);
        mWebView.registerHandler("openNativeAlbum", mOpenAlbumHandler);
        mWebView.registerHandler("openNativeVideo", mOpenVideoHandler);
        mWebView.registerHandler("openNativePay", mPayHandler);
        mWebView.registerHandler("closeNativePage", new ClosePageHandler(this));
        mWebView.registerHandler("weChatLogin", mWeChatLoginHandler);
        mWebView.registerHandler("weChatVoice", new XfunVoiceHandler(this, mWebView));
        mWebView.registerHandler("nativeRecord", new RecordHandler(this, mWebView));
//        mWebView.loadUrl("file:///android_asset/test_my_index.html");
        mWebView.loadUrl("file:///android_asset/default/index.html");
    }

    private void initWeChat() {
        api = WXAPIFactory.createWXAPI(this, WX_APPID, true);
        api.registerApp(WX_APPID);
    }

    private void initWebView() {
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSupportZoom(false);// 设置可以支持缩放
        mWebView.getSettings().setBuiltInZoomControls(false);// 设置出现缩放工具
//        mWebView.getSettings().setUseWideViewPort(true);//扩大比例的缩放
        mWebView.getSettings().setDatabaseEnabled(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setAppCacheEnabled(true);
//        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕
        mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setSaveFormData(false);
        mWebView.getSettings().setSavePassword(false);
        /* 解决空白页问题 */
        mWebView.getSettings().setDomStorageEnabled(true);//允许dom存储,部分不设置的网页会打不开
        mWebView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//允许js弹出窗口
        String cacheDirPath = this.getCacheDir().getPath();
        mWebView.getSettings().setAppCachePath(cacheDirPath); //设置  Application Caches 缓存目录
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
//        }
        mWebView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        EasyPermissions.requestPermissions(this, "录音权限", 1,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWebView.onResume();
        if (mOpenVideoHandler.isUpload) {
            mOpenVideoHandler.isUpload = false;
            mWebView.callHandler("loading", "", new CallBackFunction() {
                @Override
                public void onCallBack(String data) {

                }
            });
        }
    }

    @Override
    protected void onPause() {
        mWebView.onPause();
        super.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_CODE && data != null) {
            //获取选择的图片或者视频
            ArrayList<MediaDataBean> resultData = data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA);
            if (resultData != null && resultData.size() > 0) {
                HandlerUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.callHandler("warn2", "", new CallBackFunction() {
                            @Override
                            public void onCallBack(String data) {

                            }
                        });
                    }
                });
                if (resultData.size() == 1 && resultData.get(0).getType() == 1) {
                    //视频
                    mOpenVideoHandler.uploadFile(resultData);
                } else {
                    mOpenAlbumHandler.uploadFile(resultData);
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        mWebView.callHandler("callJsBack", "", new CallBackFunction() {
            @Override
            public void onCallBack(String data) {

            }
        });
//        if (mWebView.canGoBack()) {
//            mWebView.goBack();
//        } else {
//            finish();
//        }
    }

    @Subscribe
    public void onEvent(Object event) {
        if (event instanceof WeChatCodeEvent) {
            final String code = ((WeChatCodeEvent) event).code;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mWeChatLoginHandler.login(code);
                }
            });
        } else if (event instanceof WeChatPayEvent) {
            mPayHandler.wechatPayCallback((WeChatPayEvent) event);
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        mWebView.destroy();
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Log.i("wxq", "权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Log.i("wxq", "权限获取失败");
    }
}
